package com.lear.njava.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lear.njava.pojo.Teacher;
import com.lear.njava.service.TeacherService;
import com.lear.njava.util.MD5;
import com.lear.njava.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sms/teacherController")
public class TeacherController {

    @Autowired // 注入TeacherService
    private TeacherService teacherService;

    // GET /sms/teacherController/getTeachers/1/3?name=xx&clazzName=xx
    // 请求数据 /1/3?name=xx&clazzName=xx 分页参数，查询条件
    // 响应 Result data = 分页信息
    @GetMapping("/getTeachers/{pageNo}/{pageSize}")
    public Result getTeachers(
            @PathVariable("pageNo") Integer pageNo,
            @PathVariable("pageSize") Integer pageSize,
            Teacher teacher
    ){
        // 创建Page对象封装分页信息
        Page<Teacher> pageParam = new Page<Teacher>(pageNo, pageSize);
        // 调用服务层进行处理
        IPage<Teacher> iPage = teacherService.getTeachersByOpr(pageParam, teacher);
        // 返回结果
        return Result.ok(iPage);
    }

    // POST /sms/teacherController/saveOrUpdateTeacher
    // 请求的数据 Teacher
    // 响应Result data = null OK
    @PostMapping("saveOrUpdateTeacher")
    public Result saveOrUpdateTeacher(
            @RequestBody Teacher teacher // 传入参数
    ){
        // 判断是增加还是修改,增加无id
        Integer id = teacher.getId();
        if (null == id || 0 == id) {
            // 对密码进行加密
            String password = teacher.getPassword();
            teacher.setPassword(MD5.encrypt(password));
        }
        // 调用服务层
        teacherService.saveOrUpdate(teacher);
        return Result.ok();
    }

    // DELETE /sms/teacherController/deleteTeacher
    // 请求的数据 JSON数组 [1, 2, 3]
    // 响应 Result data = null OK
    @DeleteMapping("/deleteTeacher")
    public Result deleteTeacher(
            @RequestBody List<Integer> ids
            ){
        // 调用服务层
        teacherService.removeByIds(ids);
        return Result.ok();
    }

}
